import os
import re

from flask import Blueprint, session, render_template, request, redirect, g

from app.forms import UserUpdatePwd
from app.models import db, User, Category, Article
from app.uilts import login_auth, pwd_md5, photo_update_name

blue = Blueprint('first', __name__)

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_DIR = os.path.join(BASE_DIR, 'medias')


@blue.route('/index/', methods=['GET'])
@login_auth
def index():
    return render_template('index.html')


@blue.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        password = pwd_md5(password)
        user = User.query.filter(User.username == username, User.password == password).first()
        if user:
            session['user'] = user
            return redirect('/app/index')
    return render_template('login.html')


@blue.app_context_processor
def global_user():
    form = UserUpdatePwd()
    return dict(form=form)


@blue.route('/update_pwd/', methods=['GET', 'POST'])
@login_auth
def update_pwd():
    form = UserUpdatePwd()
    if request.method == 'POST':
        if form.validate_on_submit():
            user = User.query.filter(User.username == g.user.username).first()
            if user:
                session['user'] = ''
            user.username = form.username.data
            user.tel = form.tel.data
            user.password = pwd_md5(form.password.data)
            # db.session.add(user)
            db.session.commit()
            return redirect('/app/login/')
        else:
            return f'{form.data}'


@blue.route('/init_db/', methods=['GET', 'POST'])
def init_db():
    db.create_all()
    return '创建成功'


@blue.route('/base/')
def base():
    # user = session.get('user')
    return render_template('base.html')


@blue.route('/article/', methods=['GET', 'POST'])
@login_auth
def article():
    keywords = request.form.get('search')
    if keywords:
        ate = Article.query.filter(Article.keywords.like(f'%{keywords}%')).all()
    else:
        ate = Article.query.all()
    return render_template('article.html', data=ate)


@blue.route('/add/', methods=['GET', 'POST'])
@login_auth
def add_article():
    cgy = Category.query.all()
    if request.method == 'GET':
        return render_template('add.html', data=cgy)
    ate = Article()
    form = request.form
    ate.title = form.get('title')
    print(form.get('content'))
    ate.content = form.get('content')
    ate.keywords = form.get('keywords')
    ate.describe = form.get('describe')
    ate.category_id = form.get('category_id')
    ate.visibility = bool(form.get('visibility'))
    MEDIA_DIR = os.path.join(BASE_DIR, 'medias')
    files = request.files.get('titlepic')
    file_name = photo_update_name(files.filename)
    files.save(os.path.join(MEDIA_DIR, file_name))
    ate.titlepic = file_name
    db.session.add(ate)
    db.session.commit()
    return '保存成功'


@blue.route('/update/<int:pk>/', methods=['GET', 'POST'])
@login_auth
def update_article(pk):
    atl = Article.query.filter(Article.article_id == pk).first()
    cgys = Category.query.all()
    if request.method == 'GET':
        return render_template('update.html', atl=atl, cgys=cgys)
    form = request.form
    if form.get('title'):
        atl.title = form.get('title')
    if form.get('content'):
        atl.content = form.get('content')
    if form.get('keywords'):
        atl.keywords = form.get('keywords')
    if form.get('describe'):
        atl.describe = form.get('describe')
    if form.get('category_id'):
        atl.category_id = form.get('category_id')
    atl.visibility = bool(form.get('visibility'))
    if request.files.get('titlepic'):
        files = request.files.get('titlepic')
        file_name = photo_update_name(files.filename)
        files.save(os.path.join(MEDIA_DIR, file_name))
        atl.titlepic = file_name
    db.session.commit()
    return '保存成功'


@blue.route('/category/', methods=['GET', 'POST'])
@login_auth
def category():
    # todo  子节点计数 待完成
    if request.method == 'GET':
        categorys = Category.query.all()
        return render_template('category.html', data=categorys)
    if request.method == 'POST':
        cgy = Category()
        cgy.name = request.form.get('name')
        alias = request.form.get('alias')
        realias = r'[a-zA-Z0-9_]+'
        if not re.match(realias, alias):
            return 'error: 别名只能由字母数字下滑线组成'
        cgy.alias = request.form.get('alias')
        fid = request.form.get('fid')
        if fid:
            cgy.fid = request.form.get('fid')
        cgy.keywords = request.form.get('keywords')
        cgy.describe = request.form.get('describe')
        db.session.add(cgy)
        db.session.commit()
        return '添加成功'


@blue.route('/update_category/<int:cgyid>/', methods=['GET', 'POST'])
@login_auth
def update_category(cgyid):
    cgy = Category.query.filter(Category.category_id == cgyid).first()
    if request.method == 'GET':
        data1 = Category.query.all()
        return render_template('update_category.html', data=[data1, cgy])
    if request.method == 'POST':
        cgy.name = request.form.get('name')
        alias = request.form.get('alias')
        realias = r'[a-zA-Z0-9_]+'
        if not re.match(realias, alias):
            return 'error: 别名只能由字母数字下滑线组成'
        cgy.alias = request.form.get('alias')
        fid = request.form.get('fid')
        if fid:
            cgy.fid = request.form.get('fid')
        cgy.keywords = request.form.get('keywords')
        cgy.describe = request.form.get('describe')
        db.session.commit()
        return '更新成功'


@blue.route('/delete/<int:pk>/', methods=['DELETE'])
def delete(pk):
    print(pk)
    print(request.method)
    ate = Article.query.filter(Article.article_id == pk).first()
    db.session.delete(ate)
    db.session.commit()
    return redirect('/app/article/')
